import json
import pytz
import logging
import xlwt
import math
import werkzeug.exceptions
from datetime import datetime, timedelta, time
from itertools import groupby

from odoo import http
from odoo.addons.test_convert.tests.test_env import record
from odoo.http import request, content_disposition
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import ValidationError
from odoo.tools.misc import html_escape

_logger = logging.getLogger(__name__)


class Controller(http.Controller):

    @http.route('/download/operating/statements/report/excel/<string:start>', type='http', auth='user', website=True)
    def download_operating_statements_report_excel(self, start=None, **data):
        data = request.env['s.operating.statements'].get_data_list(start)
        x_date = datetime.strptime(start, DEFAULT_SERVER_DATE_FORMAT)
        book = xlwt.Workbook(encoding='utf-8')
        sheet = book.add_sheet('Sheet1')

        def create_style(font_height, center=True, borders=True):
            style = xlwt.XFStyle()
            font = xlwt.Font()
            font.height = font_height
            style.font = font
            if center:
                # 垂直居中 水平居中
                vertically_horizontally_centered = xlwt.Alignment()
                vertically_horizontally_centered.vert = xlwt.Alignment.VERT_CENTER
                vertically_horizontally_centered.horz = xlwt.Alignment.HORZ_CENTER
                style.alignment = vertically_horizontally_centered
            if borders:
                border = xlwt.Borders()
                border.bottom = border.top = border.left = border.right = xlwt.Borders.THIN
                style.borders = border
            return style

        field_style = create_style(15 * 15, center=True)
        for i, item in enumerate([data.get('header', [])] + data.get('lines', [[]])):
            sheet.row(i).height_mismatch = True
            sheet.row(i).height = 300
            for index, v in enumerate(item):
                sheet.write(i, index, v, field_style)

        sheet.col(0).width = 256 * 20
        sheet.col(1).width = 256 * 40
        sheet.col(2).width = 256 * 50
        file_name = f'WTT经营报表-{x_date.month}月.xls'
        response = request.make_response(None, headers=[
            ('Content-Type', 'application/vnd.ms-excel'),
            ('Content-Disposition', content_disposition(file_name))
        ])
        book.save(response.stream)
        return response



